package com.ruoyi.business.service.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.ruoyi.business.domain.ServiceItem;
import com.ruoyi.business.service.IProcessService;
import com.ruoyi.business.service.IServiceItemService;
import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.core.page.TableSupport;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ShiroUtils;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.business.mapper.CarPackageAuditMapper;
import com.ruoyi.business.domain.CarPackageAudit;
import com.ruoyi.business.service.ICarPackageAuditService;
import com.ruoyi.common.core.text.Convert;
import org.springframework.transaction.annotation.Transactional;

/**
 * 审核列表Service业务层处理
 * 
 * @author ruoyi
 * @date 2021-07-23
 */
@Service
public class CarPackageAuditServiceImpl implements ICarPackageAuditService 
{
    @Autowired
    private CarPackageAuditMapper carPackageAuditMapper;

     @Autowired
     private IProcessService processService;

     @Autowired
     private IServiceItemService serviceItemService;

    /**
     * 查询审核列表
     * 
     * @param id 审核列表ID
     * @return 审核列表
     */
    @Override
    public CarPackageAudit selectCarPackageAuditById(Long id)
    {
        return carPackageAuditMapper.selectCarPackageAuditById(id);
    }

    /**
     * 查询审核列表列表
     * 
     * @param carPackageAudit 审核列表
     * @return 审核列表
     */
    @Override
    public List<CarPackageAudit> selectCarPackageAuditList(CarPackageAudit carPackageAudit)
    {

         carPackageAudit.setCreateBy(ShiroUtils.getUserId().toString());
         List<CarPackageAudit> carPackageAudits = carPackageAuditMapper.selectCarPackageAuditList(carPackageAudit);
         for (CarPackageAudit audit : carPackageAudits) {
              //前台需要json对象解析视图,从封装的对象获取数据库里存放的序列化参数
              audit.setServiceItem(JSON.parseObject(audit.getServiceItemInfo(), ServiceItem.class));
              //根据数据中的流程实例id查询任务名称
              Task currentTask = processService.getTaskByProcessInstanceId(audit.getInstanceId());


              if (currentTask != null) {
                   //任务未结束
                   audit.setTaskId(currentTask.getId());
                   audit.setTaskName(currentTask.getName());
              }else{
                   //Task为空的情况,任务已经结束
                   audit.setTaskName("任务已结束");

              }
         }

         return carPackageAudits;
    }

    /**
     * 新增审核列表
     * 
     * @param carPackageAudit 审核列表
     * @return 结果
     */
    @Override
    public int insertCarPackageAudit(CarPackageAudit carPackageAudit)
    {
        carPackageAudit.setCreateTime(DateUtils.getNowDate());
        return carPackageAuditMapper.insertCarPackageAudit(carPackageAudit);
    }

    /**
     * 修改审核列表
     * 
     * @param carPackageAudit 审核列表
     * @return 结果
     */
    @Override
    public int updateCarPackageAudit(CarPackageAudit carPackageAudit)
    {
        return carPackageAuditMapper.updateCarPackageAudit(carPackageAudit);
    }

    /**
     * 删除审核列表对象
     * 
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteCarPackageAuditByIds(String ids)
    {
        return carPackageAuditMapper.deleteCarPackageAuditByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除审核列表信息
     * 
     * @param id 审核列表ID
     * @return 结果
     */
    @Override
    public int deleteCarPackageAuditById(Long id)
    {
        return carPackageAuditMapper.deleteCarPackageAuditById(id);
    }

     @Override
     @Transactional//涉及多张表
     public void cancelApply(String instanceId, Long carPackageAuditId) {

         //1 把快照表的信息(状态修改成撤销,审核人设置为空)
          CarPackageAudit audit = carPackageAuditMapper.selectCarPackageAuditById(carPackageAuditId);
          audit.setStatus(CarPackageAudit.STATUS_CANCEL);
          audit.setAuditors("");
          carPackageAuditMapper.updateCarPackageAudit(audit);
          //2 把服务项的状态修改成初始化
          //目前状态是   审核中
          ServiceItem item = JSON.parseObject(audit.getServiceItemInfo(), ServiceItem.class);
          item.setAuditStatus(ServiceItem.AUDITSTATUS_INIT);
          serviceItemService.updateServiceItemByCancel(item);//重新写更新逻辑,之前的方法会判断状态,如果处于审核中是不允许修改的
          //3 删除流程
          processService.deleteProcessInstance(instanceId);
     }

     @Override
     public List<CarPackageAudit> selectTodoList(CarPackageAudit carPackageAudit) {
         //先获取当前登录用的ID
          String userId = ShiroUtils.getUserId().toString();
          //根据用户id查询待办任务
          Long count =  processService.getTodoTaskCount(CarPackageAudit.DEFINITION_KEY,userId);//join
          if (count > 0) { //如果符合条件数大于0,才进行审核查询
               //获取前台传入的paggeNum和pageSize
               PageDomain pageDomain = TableSupport.buildPageRequest();
               Integer pageNum = pageDomain.getPageNum();//起始页
               Integer pageSize = pageDomain.getPageSize();//页面大小
               Integer startNum = (pageNum-1) * pageSize;//当前页 =
               List<Task> taskList = processService.selectTodoTaskList(
                       CarPackageAudit.DEFINITION_KEY,//哪一个流程
                       userId,//审批人
                       startNum,//分页起始位置
                       pageSize);//查询多少条记录
               //这里只是获得了任务集合,还要封装carPackageAuditService对象获取传入到前台的数据
               List<CarPackageAudit> resultList = new ArrayList<>();
               for (Task task : taskList) {
                    //根据任务实例id获取process实例
                    ProcessInstance instance = processService.getProcessInstanceById(task.getProcessInstanceId());
                    String businessKey = instance.getBusinessKey();
                    CarPackageAudit audit = carPackageAuditMapper.selectCarPackageAuditById(Long.parseLong(businessKey));
                    audit.setServiceItem(JSON.parseObject(audit.getServiceItemInfo(),ServiceItem.class));
                    audit.setTaskId(task.getId());//设置任务id
                    audit.setTaskName(task.getName());//设置任务名称
                    resultList.add(audit);
               }
               //需要将数据封装成page对象,里面包含分页总数和页码
               Page page = new Page();//本质上是个Arraylist
               page.setTotal(count);
               page.setPageNum(pageNum);
               page.setPageSize(pageSize);
               page.addAll(resultList);
               return page;//对象里面又包含集合,套娃妙蛙妙蛙

          }else{
               return Collections.EMPTY_LIST;
          }

     }
}
